package com.kayang;

import com.kayang.common.config.CommonConfig;
import com.kayang.webapi.config.WebApiConfig;
import com.kayang.webapi.event.Event;
import com.kayang.webapi.event.IPlugin;
import com.kayang.nadapt.util.DynamicClassLoader;
import com.kayang.nadapt.util.LogHelper;
import com.kayang.nadapt.web.HttpUtility;
import org.apache.logging.log4j.core.config.plugins.util.PluginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@EnableDiscoveryClient
@SpringBootApplication
public class WebApiApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(WebApiApplication.class, args);
    }

    @Autowired
    CommonConfig dbConfig;

    @Autowired
    WebApiConfig webApiConfig;



    @Override
    public void run(ApplicationArguments args) throws Exception {

        loadEvent();

        LogHelper.info("WebApi Startuped OK");
    }


    public  void loadEvent() {
        String path = null;
        try {
            String jarPath = new File(WebApiApplication.class.getProtectionDomain()
                    .getCodeSource()
                    .getLocation()
                    .getPath())
                    .getParentFile().getParentFile().getParentFile().getPath();

            LogHelper.info("Plguin path:" + jarPath);
            if(jarPath.startsWith("file:")){
                jarPath = jarPath.substring(5);
            }
            File dir = new File(jarPath);
            LogHelper.info("dir.isDirectory() && dir.exists():" + ((dir.isDirectory() && dir.exists()) ? "true" : "false"));
            //扫描插件
            if (dir.isDirectory() && dir.exists()) {
                File[] files = dir.listFiles((dir1, name) -> name.endsWith(".jar") && name.contains("plugin"));
                if (files != null) {
                    for (File file : files) {
                        LogHelper.info("Plguin:" + file);
                        for (Class type : loadJarTypes(file)) {
                            if (IPlugin.class.isAssignableFrom(type)) {
                                String classpath = HttpUtility.urlDecode(file.toURI().toURL().getPath());
                                DynamicClassLoader classLoader = new DynamicClassLoader(new URL[]{new URL("file:///" + classpath)}, PluginUtil.class.getClassLoader());
                                IPlugin iPlugin = (IPlugin) classLoader.loadClass(type.getName()).newInstance();
                                iPlugin.init(Event.getUnique());
                                LogHelper.info("Loaded Plugin : " + type.getName());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    private  List<Class> loadJarTypes(File file) throws IOException, ClassNotFoundException {
        List<Class> ret = new ArrayList<>();
        DynamicClassLoader loader = null;
        if (file.exists()) {
            String path = HttpUtility.urlDecode(file.toURI().toURL().getPath());
            loader = new DynamicClassLoader(new URL[]{new URL("file:///" + path)}, PluginUtil.class.getClassLoader());
            DynamicClassLoader finalLoader = loader;
            for (String name : loader.getClassName()) {
                ret.add(finalLoader.loadClass(name));
            }
        }
        return ret;
    }

}
